package com.tianze.tzkf;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.tianze.tzkf.app.App;
import com.tianze.tzkf.bean.Token;
import com.tianze.tzkf.common.ActivityManager;
import com.tianze.tzkf.net.RetrofitFactory;
import com.tianze.tzkf.utils.ApkInfoUtil;
import com.tianze.tzkf.utils.CheckWifi;
import com.tianze.tzkf.utils.ToastUtils;
import com.tianze.tzkf.utils.statusbar.StatusBarCompat;
import com.tianze.tzkf.view.ProgressDialog;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static android.provider.Settings.ACTION_WIFI_SETTINGS;


/**
 * 登录页ddda
 */
public class MainActivity extends AppCompatActivity {

    private static String TAG = MainActivity.class.toString();
    public ProgressDialog progressDialog;


    @BindView(R.id.iv_login_left)
    ImageView ivLoginLeft;
    @BindView(R.id.tv_login_title_en)
    TextView tvLoginTitleEn;
    @BindView(R.id.tv_login_title_cn)
    TextView tvLoginTitleCn;
    @BindView(R.id.et_user)
    EditText etUser;
    @BindView(R.id.ll_user)
    LinearLayout llUser;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.iv_miss_or_show)
    ImageView ivMissOrShow;
    @BindView(R.id.ll_pwd)
    LinearLayout llPwd;
    @BindView(R.id.tv_login)
    TextView tvLogin;

    private boolean isShow = false;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 隐藏顶部的状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        ButterKnife.bind(this);

        setOverflowShowingAlways();
        ActivityManager.getInstance().add(this);
        StatusBarCompat.translucentStatusBar(MainActivity.this, true);

        /**************************/
        if (CheckWifi.checkWifi() == false) {
            //当前无网络
            show_dialog("您的网络异常，请重连网络");
            Log.e("当前无网络",">>>>>>>>>>");
        }

        //
        progressDialog = new ProgressDialog();
        initEditext();

    }




    public void initEditext() {
        etUser.setText("15279603223");
        etPwd.setText("15279603223");
//        etUser.setText("17500001100");
//        etPwd.setText("123456");
    }








    @OnClick({R.id.iv_miss_or_show, R.id.tv_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_miss_or_show:
                if (!isShow) {
                    isShow = !isShow;
                    etPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); //如果被选中则显示密码
                    etPwd.setSelection(etPwd.getText().length());   //TextView默认光标在最左端，这里控制光标在最右端
                    Glide.with(this).load(R.drawable.pwd_show).into(ivMissOrShow);
                } else {
                    isShow = !isShow;
                    etPwd.setTransformationMethod(PasswordTransformationMethod.getInstance()); //如果没选中CheckBox则隐藏密码
                    etPwd.setSelection(etPwd.getText().length());
                    Glide.with(this).load(R.drawable.pwd_miss).into(ivMissOrShow);

                }
                break;
            case R.id.tv_login:
                String user = etUser.getText().toString().trim();
                String pwd = etPwd.getText().toString().trim();

                if (TextUtils.isEmpty(user) || TextUtils.isEmpty(pwd)) {
                    ToastUtils.showToast(this, "用户名或密码不能为空");
                } else {
                    login(user, pwd);
                }


                break;
        }
    }

    /**
     * 登录
     *
     * @param user 账号
     * @param pwd  密码
     */
    String serialNumber = "";

    private void login(String user, String pwd) {
        progressDialog.show(getSupportFragmentManager(),"main");
        Map<String, String> request = new HashMap<>();
        request.put("phone", user);
        request.put("password", pwd);

        serialNumber = BannerActivity.getSerialNumber();
        if (serialNumber != null && !serialNumber.equals("")) {
            request.put("terminal", serialNumber);
            Log.e("getSerialNumber", ">>" + serialNumber);
        } else {
            serialNumber = ApkInfoUtil.getANDROID_ID(this);
            Log.e("getANDROID_ID", ">>" + serialNumber);
            request.put("terminal", serialNumber);
        }


        Observable<Token> login = RetrofitFactory.getInstance(TAG).login(request);
        login.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Token>() {
                    @Override
                    public void onSubscribe(Disposable d) {
//                        progressDialog.dismiss();
                    }

                    @Override
                    public void onNext(Token token) {
                        if ( token.getCode() == 10001) {
                            saveToken(token.getData().get(0));
                            saveUser(user);
                            Intent intent_banner = new Intent(MainActivity.this,BannerActivity.class);
                            startActivity(intent_banner);
                            if (ActivityManager.getInstance() != null) {
                                ActivityManager.getInstance().finishActivity(MainActivity.this);
                            }
                            ToastUtils.showToast(MainActivity.this, token.getMsg());
                        } else {
                            Toast.makeText(MainActivity.this,token.getMsg(),Toast.LENGTH_LONG).show();
                        }
                        progressDialog.dismiss();

                    }

                    @Override
                    public void onError(Throwable e) {
                        progressDialog.dismiss();
                    }

                    @Override
                    public void onComplete() {
                        progressDialog.dismiss();
                    }
                });


    }



    /**
     * 获取用户token
     *
     * @return 返回token类
     */
    public Token.DataBean readToken() {
        SharedPreferences sp = App.getAppContext().getSharedPreferences("token_info", Context.MODE_PRIVATE);
        Token.DataBean token = new Token.DataBean();
        token.setToken(sp.getString("token", ""));
        return token;
    }

    /**
     * 保存登录token,手势密码,以及指纹
     */
    public void saveUser(String username) {
        SharedPreferences sp = App.getAppContext().getSharedPreferences("user_info", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("username", username);
        editor.commit();
    }

    /**
     * 获取用户token
     *
     * @return 返回token类
     */
    public String readUser() {
        SharedPreferences sp = App.getAppContext().getSharedPreferences("user_info", Context.MODE_PRIVATE);
        String username = sp.getString("username", "");
        return username;
    }

    /**
     * 保存登录token,手势密码,以及指纹
     */
    public void saveToken(Token.DataBean token) {
        SharedPreferences sp = App.getAppContext().getSharedPreferences("token_info", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("token", token.getToken());
        editor.commit();
    }


    private void setOverflowShowingAlways() {
        try {
            ViewConfiguration config = ViewConfiguration.get(this);
            Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 无网络的对话框
     */
    AlertDialog alertDialog_main;
    public void show_dialog(String dialog_str) {
        Activity activity = ActivityManager.getInstance().currentActivity();
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("提示:");
        builder.setMessage(dialog_str);
        builder.setCancelable(false);
        builder.setPositiveButton("刷新网络", null);
        builder.setNegativeButton("去连接网络", null);
        alertDialog_main = builder.create();


        alertDialog_main.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                Button positionButton=alertDialog_main.getButton(AlertDialog.BUTTON_POSITIVE);
                Button negativeButton=alertDialog_main.getButton(AlertDialog.BUTTON_NEGATIVE);
                positionButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (CheckWifi.checkWifi() == true){
                            Toast.makeText(MainActivity.this,"网络已经连接",Toast.LENGTH_SHORT).show();
                            if (alertDialog_main != null) {
                                alertDialog_main.dismiss();
                                alertDialog_main = null;
                            }


                        }else {
                            Toast.makeText(MainActivity.this,"网络还未连接",Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                negativeButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent_Internet = new Intent(ACTION_WIFI_SETTINGS);
                        startActivity(intent_Internet);

                    }
                });
            }
        });
        alertDialog_main.show();

    }

}
